package com.loutick.basicforapp.controller;

import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.loutick.basicforapp.entity.TUser;
import com.loutick.basicforapp.entity.TVerification;
import com.loutick.basicforapp.jsonbean.BasicRequestBean;
import com.loutick.basicforapp.jsonbean.RequestJsonMainBean;
import com.loutick.basicforapp.message.BasicMessage;
import com.loutick.basicforapp.message.ThirdLoginMessage;
import com.loutick.basicforapp.message.UserInfoMessage;
import com.loutick.basicforapp.message.VerificationMessage;
import com.loutick.basicforapp.service.IUserService;
import com.loutick.basicforapp.service.IVerificationService;
import com.loutick.basicforapp.sms.SmsClient;
import com.loutick.basicforapp.util.MySessionContext;
import com.loutick.basicforapp.util.PasswordDes;



@Controller
@RequestMapping("/user")
public class UserController {
	
	private static Logger logger = Logger.getLogger(UserController.class);
	@Resource
	private IUserService userService;
	@Resource
	private IVerificationService verificationService ;
	
//	@RequestMapping("/showUser")
//	public String toIndex(HttpServletRequest request,Model model){
//		int userId = Integer.parseInt(request.getParameter("id"));
//		User user = this.userService.getUserById(userId);
//		model.addAttribute("user", user);
//		return "showUser";
//	}
	
	/**
	 * 客户端调用入口
	 * @param sessionId   客户端sessionId
	 * @param message     客户端请求信息
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/userapi")
	public @ResponseBody Map<String , Object> toUserApi(@RequestParam String sessionId ,@RequestParam String message,HttpServletRequest request,Model model){
		//返回结果集
		Map<String , Object> modelMap = new HashMap<String , Object>();
		
		HttpSession session = null;
		//判断是否有传入sessionId,如果有传入 直接使用
		logger.info("客户端传入 sessionId:" + sessionId) ;
		logger.info("客户端传入 message:" + message) ;
		
		//没有正确传入message
		if(message== null || message.equals("")) {
			BasicMessage b = new BasicMessage();
			b.setCode("1");
			b.setMsg("message参数不存在");
			modelMap.put("res", b);
			return modelMap;
		}
		BasicRequestBean basicRequestBean = null;
		RequestJsonMainBean jsonMainBean = null;
		try {
			basicRequestBean = JSON.parseObject(message,BasicRequestBean.class);
			jsonMainBean = basicRequestBean.getFirstReq() ;
		} catch (Exception e) {
			BasicMessage b = new BasicMessage();
			b.setCode("1");
			b.setMsg("message参数解析出错");
			modelMap.put("res", b);
			return modelMap;
		}
		
		String reqType = jsonMainBean.getReqType() ;
		
		//依赖客户端传入的sessionId获取session;
		if(sessionId!=null&&MySessionContext.getSession(sessionId)!=null)
		{
			session = MySessionContext.getSession(sessionId);
			logger.info("客户端传入 sessionId有效") ;
		}
		//客户端传入的sessionId无效，重新获取session，并获取sessionId;
		else{
			
			if(reqType.equals("1001")||reqType.equals("1002")||reqType.equals("1007")){
				session =  request.getSession() ;
				sessionId = session.getId();
				logger.info("客户端传入 sessionId无效， 创建新的session；新的sessionId:" + sessionId) ;
			}
			else{
				BasicMessage b = new BasicMessage();
				b.setCode("1");
				b.setMsg("session不存在，请重新登录");
				modelMap.put("res", b);
				return modelMap;
			}
		}
		
		
		
		//第三方登录
		if(reqType.equals("1001")){
			return thirdLogin(jsonMainBean,session);
		}
		//用户注册
		else if(reqType.equals("1002")){
			return registerUser(jsonMainBean,session);
		}
		//修改密码
		else if(reqType.equals("1003")){
			return changePassword(jsonMainBean,session);
		}
		//修改用户信息
		else if(reqType.equals("1004")){
			return changeUserInfo(jsonMainBean,session);
		}
		//修改登录手机号
		else if(reqType.equals("1005")){
			return changeMobileNum(jsonMainBean,session);
		}
		//忘记密码    
		else if(reqType.equals("1006")){
			return forgetPassword(jsonMainBean);
		}
		//登录
		else if(reqType.equals("1007")){
			return login(jsonMainBean,session);
		}
		//注销
		else if(reqType.equals("1008")){
			return destroyUser(jsonMainBean,session);
		}
		//下发短信
		else if(reqType.equals("1009")){
			return messageSend(jsonMainBean);
		}
		return modelMap;
	}
	/**
	 * 2.1.第三方账号登录（QQ、微信、微博）
	 * @param paramString
	 * @return
	 */
	private Map<String , Object> thirdLogin(RequestJsonMainBean jsonObject,HttpSession session){
		//"{'req':[{'reqType':'1001','usid':'a00001','channel':'1'}]}";
		//返回结果集
		Map<String , Object> modelMap = new HashMap<String , Object>();
		String usid = jsonObject.getUsid();
		String channel = jsonObject.getChannel();
		//==============================================
		//业务功能实现
		TUser tuser = new TUser();
		tuser.setUsid(usid);
		tuser.setChannel(channel);
		int userID = this.userService.getUserByChannel(tuser);
		//==============================================
		ThirdLoginMessage t = new ThirdLoginMessage();
		t.setCode("0");
		t.setMsg("登录成功");
		t.setUserID(String.valueOf(userID));
		modelMap.put("res", t);
		modelMap.put("sessionId", session.getId());
		return modelMap;
	}
	/**
	 * 2.2.用户注册
	 * @param paramString
	 * @return
	 */
	private Map<String , Object> registerUser(RequestJsonMainBean jsonObject,HttpSession session){
		//"{'req':[{'reqType':'1002','phoneNumber':'17001980001','nickName':'测试3','name':'测试线3','email':'17001980001@sina.com','password':'111111'}]}";
		//"{'req':[{'reqType':'1002','phoneNumber':'17001980003','nickName':'test4','name':'testline4','email':'17001980003@sina.com','password':'111111'}]}";
		//"{'req':[{'reqType':'1002','phoneNumber':'17001980011','nickName':'加密用户1','name':'加密用户1','email':'17001980011@sina.com','password':'111111'}]}";
		//返回结果集
		Map<String , Object> modelMap = new HashMap<String , Object>();
		String phoneNumber = jsonObject.getPhoneNumber();
		String nickName = jsonObject.getNickName();
		String name = jsonObject.getName();
		String email = jsonObject.getEmail();
		String password = jsonObject.getPassword();
		//==============================================
		//业务功能实现
		TUser tuser = null ;
		tuser = this.userService.selectByPhoneNumber(phoneNumber);
		//验证手机号是否已经被注册过
		if(tuser!=null){
			BasicMessage t = new BasicMessage();
			t.setCode("1");
			t.setMsg("该手机号已经注册");
			modelMap.put("res", t);
			return modelMap;
		}else{
			tuser = new TUser();
			tuser.setPhonenumber(phoneNumber);
			tuser.setName(name);
			tuser.setNickname(nickName);
			tuser.setEmail(email);
			tuser.setPassword(PasswordDes.makeMD5(password));
			int recordnum = this.userService.registerUser(tuser);
			//==============================================
			if(recordnum>0){
				ThirdLoginMessage t = new ThirdLoginMessage();
				t.setCode("0");
				t.setMsg("注册成功");
				t.setUserID(String.valueOf(tuser.getUserid()));
				modelMap.put("res", t);
				
				
			}else{
				BasicMessage t = new BasicMessage();
				t.setCode("1");
				t.setMsg("数据插入失败");
				modelMap.put("res", t);
			}
			modelMap.put("sessionId", session.getId());
			return modelMap;
		}
	}
	
	/**
	 * 2.3.修改密码
	 * @param paramString
	 * @return
	 */
	private Map<String , Object> changePassword(RequestJsonMainBean jsonObject,HttpSession session){
		//"{'req':[{'reqType':'1003','userID':'6','oldPwd':'1','newPwd':'333'}]}";
		//返回结果集
		Map<String , Object> modelMap = new HashMap<String , Object>();
		String userID = jsonObject.getUserID();
		String oldPwd = jsonObject.getOldPwd();
		String newPwd = jsonObject.getNewPwd();
		//==============================================
		//业务功能实现
		TUser tuser = null ;
		//验证旧密码是否正确
		tuser = this.userService.getUserById(Integer.parseInt(userID));
		if(!tuser.getPassword().equals(PasswordDes.makeMD5(oldPwd))){
			BasicMessage b = new BasicMessage();
			b.setCode("1");
			b.setMsg("旧密码不匹配");
			modelMap.put("res", b);
			modelMap.put("sessionId", session.getId());
			return modelMap;
		}
		//通过验证修改密码
		tuser = new TUser();
		tuser.setUserid(Integer.parseInt(userID));
		tuser.setPassword(PasswordDes.makeMD5(newPwd));
		int recordnum = this.userService.updateByPrimaryKey(tuser);
		
		//==============================================
		if(recordnum>0){
			BasicMessage b = new BasicMessage();
			b.setCode("0");
			b.setMsg("修改密码成功");
			modelMap.put("res", b);
		}else{
			BasicMessage b = new BasicMessage();
			b.setCode("1");
			b.setMsg("修改密码失败");
			modelMap.put("res", b);
		}
		modelMap.put("sessionId", session.getId());
		return modelMap;
	}
	
	/**
	 * 2.4.修改用户基本信息
	 * @param paramString
	 * @return
	 */
	private Map<String , Object> changeUserInfo(RequestJsonMainBean jsonObject,HttpSession session){
		//"{'req':[{'reqType':'1004','userID':'8','nickName':'1','name':'1','email':'1@qq.com'}]}";
		//返回结果集
		Map<String , Object> modelMap = new HashMap<String , Object>();
		String userID = jsonObject.getUserID();
		String nickName = jsonObject.getNickName();
		String name = jsonObject.getName();
		String email = jsonObject.getEmail();
		//==============================================
		//业务功能实现
		TUser tuser = null ;
		tuser = new TUser();
		tuser.setUserid(Integer.parseInt(userID));
		tuser.setNickname(nickName);
		tuser.setName(name);
		tuser.setEmail(email);
		int recordnum = this.userService.updateByPrimaryKey(tuser);
		
		//==============================================
		if(recordnum>0){
			UserInfoMessage b = new UserInfoMessage();
			b.setCode("0");
			b.setUserID(userID);
			b.setNickName(nickName);
			b.setName(name);
			b.setEmail(email);
			b.setMsg("修改用户信息成功");
			modelMap.put("res", b);
			
		}else{
			BasicMessage b = new BasicMessage();
			b.setCode("1");
			b.setMsg("修改用户信息失败");
			modelMap.put("res", b);
		}
		modelMap.put("sessionId", session.getId());
		return modelMap;
	}
	
	/**
	 * 2.5.修改登录手机号
	 * @param paramString
	 * @return
	 */
	private Map<String , Object> changeMobileNum(RequestJsonMainBean jsonObject,HttpSession session){
		//"{'req':[{'reqType':'1005','userID':'1000123','type':'1','randPWD':'1','oldPhoneNumber':'1','newPhoneNumber':'1'}]}";
		//返回结果集
		Map<String , Object> modelMap = new HashMap<String , Object>();
		String userID = jsonObject.getUserID();
		String type = jsonObject.getType();
		String randPWD = jsonObject.getRandPwd();
		String oldPhoneNumber = jsonObject.getOldPhoneNumber();
		String newPhoneNumber = jsonObject.getNewPhoneNumber();
		//==============================================
		//业务功能实现
		//1.获取该userid对应的随机验证码，判断验证码是否过期；
		TVerification v = new TVerification();
		v.setUserid(Integer.valueOf(userID));
		v = verificationService.getVerificationCodeByPhoneNumber(v);
		Calendar c = Calendar.getInstance();
		if(v.getInvalidtime().before(c.getTime())){
			//2.如果验证码过期拒绝修改，并将过期记录设置为失效；
			TVerification record = new TVerification();
			record.setCodeid(v.getCodeid());
			record.setCodestatus(false);
			int success = verificationService.updateByCodeId(record);
			BasicMessage b = new BasicMessage();
			b.setCode("1");
			b.setMsg("验证码已经过期");
			modelMap.put("res", b);
			modelMap.put("sessionId", session.getId());
			return modelMap;
		}
		else{
			TUser tuser = null ;
			tuser = new TUser();
			tuser = this.userService.getUserById(Integer.parseInt(userID));
			//3.如果没有过期确认内外验证码是否一致，如果验证码和输入旧手机号和系统注册手机号一致修改；如果不一致拒绝修改
			if(v.getCodenumber().equals(randPWD)) {
				if(tuser.getPhonenumber().equals(oldPhoneNumber)){
					tuser = new TUser();
					tuser.setUserid(Integer.parseInt(userID));
					tuser.setPhonenumber(newPhoneNumber);
					int recordnum = this.userService.updateByPrimaryKey(tuser);
				}else{
					BasicMessage b = new BasicMessage();
					b.setCode("1");
					b.setMsg("输入旧手机号和注册手机号不一致");
					modelMap.put("res", b);
					modelMap.put("sessionId", session.getId());
					return modelMap;
				}
			}else{
				BasicMessage b = new BasicMessage();
				b.setCode("1");
				b.setMsg("验证码不正确");
				modelMap.put("res", b);
				modelMap.put("sessionId", session.getId());
				return modelMap;
			}
		}
		
		//==============================================
		ThirdLoginMessage b = new ThirdLoginMessage();
		b.setCode("0");
		b.setUserID(userID);
		b.setMsg("修改手机号成功");
		modelMap.put("res", b);
		modelMap.put("sessionId", session.getId());
		return modelMap;
	}
	
	/**
	 * 2.6.用户忘记密码
	 * @param paramString
	 * @return
	 */
	private Map<String , Object> forgetPassword(RequestJsonMainBean jsonObject){
		//"{'req':[{'reqType':'1006','phoneNumber':'17001980003','randPwd':'410155','newPwd':'222222'}]}";
		//返回结果集
		Map<String , Object> modelMap = new HashMap<String , Object>();
		String phoneNumber = jsonObject.getPhoneNumber();
		String randPwd = jsonObject.getRandPwd();
		String newPwd = jsonObject.getNewPwd();
		//==============================================
		//业务功能实现
		//1.基于手机号确认验证码是否过期，如果过期将验证码注销
		TVerification v = new TVerification();
		v.setPhonenumber(phoneNumber);
		v = verificationService.getVerificationCodeByPhoneNumber(v);
		if(v == null){
			BasicMessage b = new BasicMessage();
			b.setCode("1");
			b.setMsg("该手机未申请验证码");
			modelMap.put("res", b);
			return modelMap;
		}
		Calendar c = Calendar.getInstance();
		if(v.getInvalidtime().before(c.getTime())){
			//2.如果验证码过期拒绝修改，并将过期记录设置为失效；
			TVerification record = new TVerification();
			record.setCodeid(v.getCodeid());
			record.setCodestatus(true);
			int success = verificationService.updateByCodeId(record);
			BasicMessage b = new BasicMessage();
			b.setCode("1");
			b.setMsg("验证码已经过期");
			modelMap.put("res", b);
			return modelMap;
		}
		//2.如果没有过期，修改密码
		else{
			if(v.getCodenumber().equals(randPwd)) {
				TUser tuser = null ;
				tuser = new TUser();
				tuser = this.userService.selectByPhoneNumber(phoneNumber);
				if(tuser == null){
					BasicMessage b = new BasicMessage();
					b.setCode("1");
					b.setMsg("该手机没有注册");
					modelMap.put("res", b);
					return modelMap;
				}
				tuser.setPassword(PasswordDes.makeMD5(newPwd));
				int success = this.userService.updateByPrimaryKey(tuser);
			}else{
				BasicMessage b = new BasicMessage();
				b.setCode("1");
				b.setMsg("验证码不正确");
				modelMap.put("res", b);
				return modelMap;
			}
		}
		
		//==============================================
		BasicMessage b = new BasicMessage();
		b.setCode("0");
		b.setMsg("修改密码成功");
		modelMap.put("res", b);
		return modelMap;
	}
	
	/**
	 * 2.7.登陆
	 * @param paramString
	 * @return
	 */
	private Map<String , Object> login(RequestJsonMainBean jsonObject,HttpSession session){
		//"{'req':[{'reqType':'1007','phoneNumber':'17001980003','password':'111111'}]}";
		//返回结果集
		Map<String , Object> modelMap = new HashMap<String , Object>();
		String phoneNumber = jsonObject.getPhoneNumber();
		String password = jsonObject.getPassword();
		//==============================================
		//业务功能实现
		TUser tuser = null ;
		tuser = this.userService.selectByPhoneNumber(phoneNumber);
		if(tuser!=null&&PasswordDes.makeMD5(password).equals(tuser.getPassword())){
			UserInfoMessage b = new UserInfoMessage();
			b.setCode("0");
			b.setMsg("登录成功");
			b.setUserID(String.valueOf(tuser.getUserid()));
			b.setNickName(tuser.getNickname());
			b.setPassword(tuser.getPassword());
			modelMap.put("res", b);
			
		}
		else{
			BasicMessage b = new BasicMessage();
			b.setCode("1");
			b.setMsg("登录失败");
			modelMap.put("res", b);
			
		}
		modelMap.put("sessionId", session.getId());
		return modelMap;
		
	}
	
	/**
	 * 注销  
	 * @param paramString
	 * @param session
	 * @return
	 */
	private Map<String , Object> destroyUser(RequestJsonMainBean jsonObject,HttpSession session){
		//"{'req':[{'reqType':'1008','userID':'1000123'}]}";
		//返回结果集
		Map<String , Object> modelMap = new HashMap<String , Object>();
		String userID = jsonObject.getUserID();
		session.invalidate();
		BasicMessage b = new BasicMessage();
		b.setCode("0");
		b.setMsg("注销成功");
		modelMap.put("res", b);
		return modelMap;
	}
	
	/**
	 * 2.9.短信下发接口
	 * @param paramString
	 * @return
	 */
	private Map<String , Object> messageSend(RequestJsonMainBean jsonObject){
		//"{'req':[{'reqType':'1009','phoneNumber':'15396064551','purposeType':'1'}]}";
		String randPwd = null;
		//返回结果集
		Map<String , Object> modelMap = new HashMap<String , Object>();
		String phoneNumber = jsonObject.getPhoneNumber();
		String purposeType = jsonObject.getPurposeType();
		//==============================================
		//业务功能实现
		//1.purposeType =1  注册请求，在验证码系统中是以手机号为识别标志；
		if(purposeType.equals("1")){
			TVerification v = new TVerification();
			v.setPhonenumber(phoneNumber);
			v = verificationService.getVerificationCodeByPhoneNumber(v);
			//2.当系统中没有对应手机的验证码时，生成验证码并下发；
			if(v==null){
				int i = verificationService.insertVerificateionByPhoneNumber(phoneNumber);
				if(i==0){
					BasicMessage b = new BasicMessage();
					b.setCode("1");
					b.setMsg("验证码生成失败");
					modelMap.put("res", b);
					return modelMap;
				}
				v = new TVerification();
				v.setPhonenumber(phoneNumber);
				v = verificationService.getVerificationCodeByPhoneNumber(v);
				randPwd = v.getCodenumber() ;
			}
			else{
				Calendar c = Calendar.getInstance();
				if(v.getInvalidtime().before(c.getTime())){
					//3.如果验证码过期拒绝修改，并将过期记录设置为失效；
					TVerification record = new TVerification();
					record.setCodeid(v.getCodeid());
					record.setCodestatus(true);
					int success = verificationService.updateByCodeId(record);
					int i = verificationService.insertVerificateionByPhoneNumber(phoneNumber);
					if(i==0){
						BasicMessage b = new BasicMessage();
						b.setCode("1");
						b.setMsg("验证码生成失败");
						modelMap.put("res", b);
						return modelMap;
					}
					v = new TVerification();
					v.setPhonenumber(phoneNumber);
					v = verificationService.getVerificationCodeByPhoneNumber(v);
					randPwd = v.getCodenumber() ;
				}else{
					randPwd = v.getCodenumber() ;
				}
				
			}
		}
		//2.purposeType =2  忘记密码，是以userID为识别标志；
		else{
			TUser tuser = null ;
			tuser = new TUser();
			tuser = this.userService.selectByPhoneNumber(phoneNumber);
			TVerification v = new TVerification();
			v.setUserid(tuser.getUserid());
			v = verificationService.getVerificationCodeByPhoneNumber(v);
			if(v==null){
				int i = verificationService.insertVerificateionByUserID(tuser.getUserid(),phoneNumber); 
				if(i==0){
					BasicMessage b = new BasicMessage();
					b.setCode("1");
					b.setMsg("验证码生成失败");
					modelMap.put("res", b);
					return modelMap;
				}
				v = new TVerification();
				v.setUserid(tuser.getUserid());
				v = verificationService.getVerificationCodeByPhoneNumber(v);
				randPwd = v.getCodenumber() ;
			}
			else{
				Calendar c = Calendar.getInstance();
				if(v.getInvalidtime().before(c.getTime())){
					//4.如果验证码过期拒绝修改，并将过期记录设置为失效；
					TVerification record = new TVerification();
					record.setCodeid(v.getCodeid());
					record.setCodestatus(true);
					int success = verificationService.updateByCodeId(record);
					int i = verificationService.insertVerificateionByUserID(tuser.getUserid(),phoneNumber); 
					if(i==0){
						BasicMessage b = new BasicMessage();
						b.setCode("1");
						b.setMsg("验证码生成失败");
						modelMap.put("res", b);
						return modelMap;
					}
					v = new TVerification();
					v.setUserid(tuser.getUserid());
					v = verificationService.getVerificationCodeByPhoneNumber(v);
					randPwd = v.getCodenumber() ;
				}else{
					randPwd = v.getCodenumber() ;
				}
				randPwd = v.getCodenumber() ;
			}
		}
		//==============================================
		//下发短信
//		SmsClient client = new SmsClient();
//		long task_id = 00000000000;
//		try {
//			client.sendSms(phoneNum, "内容", "sp_code", task_id);
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
		//==============================================
		VerificationMessage vm = new VerificationMessage();
		vm.setCode("0");
		vm.setMsg("短信下发成功");
		vm.setRandPwd(randPwd);
		modelMap.put("res", vm);
		return modelMap;
	}
	
}
